﻿using GadgetStore.Data;
using GadgetStore.Data.Models;
using GadgetStore.Web.Adapters.Interfaces;
using GadgetStore.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GadgetStore.Web.Adapters
{
    public class GadgetAdapter : IGadget
    {
        public GadgetVM GetOneGadget(int id)
        {
            ApplicationDbContext Db = new ApplicationDbContext();
            GadgetVM vm = new GadgetVM();
            vm.Gadget = Db.Gadgets.Where(g => g.Id == id).FirstOrDefault();
            vm.Pictures = Db.Pictures.Where(p => p.GadgetId == id).ToList();
            return vm;
        }
        public List<Gadget> GetAllGadgets()
        {
            ApplicationDbContext Db = new ApplicationDbContext();
            return Db.Gadgets.ToList();
        }
        public int NewGadget(Gadget gadget)
        {
            ApplicationDbContext Db = new ApplicationDbContext();
            Gadget newGadget = new Gadget(gadget.Name, gadget.Descript, gadget.TopPict, gadget.Price, gadget.Qty, gadget.ProductType);
            Db.Gadgets.Add(newGadget);
            Db.SaveChanges();
            return newGadget.Id;
        }
        public void DeleteGadget(int id)
        {
            ApplicationDbContext Db = new ApplicationDbContext();
            Gadget Gadget = Db.Gadgets.Where(g => g.Id == id).FirstOrDefault();
            List<Picture> Pictures = Db.Pictures.Where(p => p.GadgetId == id).ToList();
            foreach (var pict in Pictures)
            {
                Db.Pictures.Remove(pict);
            }
            Db.SaveChanges();
            Db.Gadgets.Remove(Gadget);
            Db.SaveChanges();
        }
        public int UpdateGadget(Gadget gadget)
        {
            ApplicationDbContext Db = new ApplicationDbContext();
            Gadget EditedGadget = Db.Gadgets.Where(g => g.Id == gadget.Id).FirstOrDefault();
            EditedGadget.Name = gadget.Name;
            EditedGadget.Descript = gadget.Descript;
            EditedGadget.TopPict = gadget.TopPict;
            EditedGadget.Price = gadget.Price;
            EditedGadget.Qty = gadget.Qty;
            EditedGadget.ProductType = gadget.ProductType;
            Db.SaveChanges();
            return EditedGadget.Id;
        }
    }
}